import { reqgetgoods,reqgetcate } from "../../http/api";

//state
const initState = {
    cate:[],
    goods:[],
    n:0
}

//action type
const TYPES = {
    CATE_CAHNGE_CATE:"CATE_CHANGE_CATE",
    CATE_CHANGE_GOODS:"CATE_CHANGE_GOODS",
    CATE_CHANGE_N:"CATE_CHANGE_N"
}

//reducer
const reducer = (state = initState, action) => {
    switch (action.type) {

        case TYPES.CATE_CAHNGE_CATE:
            return {
                ...state,
                cate:action.cate,
            };
        case TYPES.CATE_CHANGE_GOODS:
            return {
                ...state,
                goods:action.goods,
            }
        case TYPES.CATE_CHANGE_N:
            return {
                ...state,
                n:action.n,
            }        
        default:
            return state;
    }
}

//action creator
export const actions = {
    changeCate:(cate) => ({type:TYPES.CATE_CAHNGE_CATE,cate}),
    reqCate:() => (dispatch,getState) =>{
        let cate = getCate(getState());
        if(cate.length>0){
            return ;
        }
        reqgetcate().then((res)=>{
            dispatch(actions.changeCate(res.data.list));
        });
    },
    changeGoods:(goods) => ({type:TYPES.CATE_CHANGE_GOODS,goods}),
    reqGoods:() => (dispatch,getState) =>{
        let goods = getGoods(getState());
        if(goods.length>0){
            return ;
        }
        reqgetgoods().then((res)=>{
            dispatch(actions.changeGoods(res.data.list));
        });
    },
    cahngeN:n =>({ type:TYPES.CATE_CHANGE_N ,n})
}

//selector导出数据给组件
export const getGoods = state => state.cate.goods;
export const getCate = state => state.cate.cate;
export const getN = state => state.cate.n;

//导出reducer
export default reducer;